<template>
  <div class="login-account">
    <el-form
      label-position="top"
      label-width="60px"
      :rules="rules"
      :model="account"
      ref="formRef"
    >
      <el-form-item label="" prop="userNameOrEmailAddress">
        <el-input v-model="account.userNameOrEmailAddress">
          <template #prefix>
            <i class="el-icon-user-solid"></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="password">
        <el-input v-model="account.password" show-password>
          <template #prefix>
            <i class="el-icon-star-on"></i>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElForm } from 'element-plus'
import { defineComponent, reactive, ref } from 'vue'
// 导入config封装
import { rules } from '../config/account-config'
import LocalCache from '@/utils/cache'
import { useStore } from 'vuex'

export default defineComponent({
  setup() {
    const store = useStore() // 拿到vuex
    const account = reactive({
      userNameOrEmailAddress: LocalCache.getCache('userNameOrEmailAddress'),
      password: LocalCache.getCache('password'),
    })
    const formRef = ref<InstanceType<typeof ElForm>>()
    const loginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          console.log('account登录成功')
          // 1.记住密码 判断是否记住密码
          if (isKeepPassword) {
            // 本地缓存
            LocalCache.setCache(
              'userNameOrEmailAddress',
              account.userNameOrEmailAddress,
            )
            LocalCache.setCache('password', account.password)
            console.log(isKeepPassword)
          } else {
            // 删除密码
            LocalCache.deleteCache('password')
          }

          // 2.开始登录验证
          store.dispatch('login/accountLoginOrdinary', { ...account })
        } else {
          console.log('登录失败')
        }
      })
    }
    // 编写好规则
    return { account, rules, formRef, loginAction }
  },
})
</script>

<style scoped></style>
